import 'package:flutter/material.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../widgets/advanced_rich_text_editor.dart';
import '../../widgets/rich_text_viewer.dart';

/// 发布文章页面
/// 支持富文本编辑和预览
class PublishArticlePage extends StatefulWidget {
  final String? initialTitle;
  final String? initialContent;
  final String? postId; // 编辑模式时的文章ID

  const PublishArticlePage({
    super.key,
    this.initialTitle,
    this.initialContent,
    this.postId,
  });

  @override
  State<PublishArticlePage> createState() => _PublishArticlePageState();
}

class _PublishArticlePageState extends State<PublishArticlePage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _summaryController = TextEditingController();
  final ApiService _apiService = ApiService();
  
  String _htmlContent = '';
  bool _isPublishing = false;
  bool _isPreviewMode = false;
  
  // 文章设置
  String _visibility = 'public'; // public, private, friends
  List<String> _tags = [];
  final TextEditingController _tagController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    
    // 初始化数据
    if (widget.initialTitle != null) {
      _titleController.text = widget.initialTitle!;
    }
    if (widget.initialContent != null) {
      _htmlContent = widget.initialContent!;
    }
    
    _tabController.addListener(() {
      setState(() {
        _isPreviewMode = _tabController.index == 1;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _titleController.dispose();
    _summaryController.dispose();
    _tagController.dispose();
    super.dispose();
  }

  /// 发布文章
  Future<void> _publishArticle() async {
    if (_titleController.text.trim().isEmpty) {
      _showError('请输入文章标题');
      return;
    }
    
    if (_htmlContent.trim().isEmpty) {
      _showError('请输入文章内容');
      return;
    }

    setState(() {
      _isPublishing = true;
    });

    try {
      final Map<String, dynamic> articleData = {
        'postType': 'article',
        'title': _titleController.text.trim(),
        'content': _htmlContent,
        'summary': _summaryController.text.trim().isNotEmpty 
            ? _summaryController.text.trim() 
            : _generateSummary(),
        'visibility': _visibility,
        'tags': _tags,
        'article': {
          'title': _titleController.text.trim(),
          'content_html': _htmlContent,
          'summary': _summaryController.text.trim().isNotEmpty 
              ? _summaryController.text.trim() 
              : _generateSummary(),
        },
      };

      Logger.d('PUBLISH_ARTICLE', '发布文章数据: $articleData');

      final result = await _apiService.publishPost(articleData);
      
      if (result['success'] == true) {
        Logger.d('PUBLISH_ARTICLE', '文章发布成功');
        _showSuccess('文章发布成功！');
        
        // 延迟返回，让用户看到成功提示
        await Future.delayed(const Duration(seconds: 1));
        if (mounted) {
          Navigator.of(context).pop(true); // 返回true表示发布成功
        }
      } else {
        _showError('发布失败：${result['message'] ?? '未知错误'}');
      }
    } catch (e) {
      Logger.e('PUBLISH_ARTICLE', '发布文章失败: $e');
      _showError('发布失败：$e');
    } finally {
      if (mounted) {
        setState(() {
          _isPublishing = false;
        });
      }
    }
  }

  /// 生成摘要
  String _generateSummary() {
    // 从HTML内容中提取纯文本作为摘要
    String plainText = _htmlContent
        .replaceAll(RegExp(r'<[^>]*>'), '') // 移除HTML标签
        .replaceAll(RegExp(r'\s+'), ' ') // 合并空白字符
        .trim();
    
    // 截取前150个字符作为摘要
    if (plainText.length > 150) {
      return plainText.substring(0, 150) + '...';
    }
    return plainText;
  }

  /// 添加标签
  void _addTag() {
    final tag = _tagController.text.trim();
    if (tag.isNotEmpty && !_tags.contains(tag) && _tags.length < 5) {
      setState(() {
        _tags.add(tag);
        _tagController.clear();
      });
    }
  }

  /// 移除标签
  void _removeTag(String tag) {
    setState(() {
      _tags.remove(tag);
    });
  }

  /// 显示错误信息
  void _showError(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 显示成功信息
  void _showSuccess(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.green,
        ),
      );
    }
  }

  /// 构建标题输入区域
  Widget _buildTitleSection() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey[200]!)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextField(
            controller: _titleController,
            decoration: const InputDecoration(
              hintText: '请输入文章标题...',
              border: InputBorder.none,
              hintStyle: TextStyle(color: Colors.grey),
            ),
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
            maxLines: 2,
          ),
          const SizedBox(height: 12),
          TextField(
            controller: _summaryController,
            decoration: const InputDecoration(
              hintText: '请输入文章摘要（可选，系统会自动生成）...',
              border: InputBorder.none,
              hintStyle: TextStyle(color: Colors.grey, fontSize: 14),
            ),
            style: const TextStyle(fontSize: 14),
            maxLines: 3,
          ),
        ],
      ),
    );
  }

  /// 构建标签和设置区域
  Widget _buildTagsAndSettings() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey[200]!)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标签输入
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _tagController,
                  decoration: const InputDecoration(
                    hintText: '添加标签（最多5个）',
                    border: OutlineInputBorder(),
                    contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                  onSubmitted: (_) => _addTag(),
                ),
              ),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: _addTag,
                child: const Text('添加'),
              ),
            ],
          ),
          
          // 标签显示
          if (_tags.isNotEmpty) ...[
            const SizedBox(height: 12),
            Wrap(
              spacing: 8,
              runSpacing: 4,
              children: _tags.map((tag) => Chip(
                label: Text(tag),
                deleteIcon: const Icon(Icons.close, size: 16),
                onDeleted: () => _removeTag(tag),
              )).toList(),
            ),
          ],
          
          const SizedBox(height: 16),
          
          // 可见性设置
          Row(
            children: [
              const Text('可见性：', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(width: 12),
              DropdownButton<String>(
                value: _visibility,
                items: const [
                  DropdownMenuItem(value: 'public', child: Text('公开')),
                  DropdownMenuItem(value: 'friends', child: Text('仅好友')),
                  DropdownMenuItem(value: 'private', child: Text('私密')),
                ],
                onChanged: (value) {
                  if (value != null) {
                    setState(() {
                      _visibility = value;
                    });
                  }
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.postId != null ? '编辑文章' : '发布文章'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 1,
        actions: [
          if (_isPublishing)
            const Padding(
              padding: EdgeInsets.all(16),
              child: SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              ),
            )
          else
            TextButton(
              onPressed: _publishArticle,
              child: const Text(
                '发布',
                style: TextStyle(
                  color: Colors.blue,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '编辑'),
            Tab(text: '预览'),
          ],
        ),
      ),
      body: Column(
        children: [
          _buildTitleSection(),
          _buildTagsAndSettings(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                // 编辑模式
                AdvancedRichTextEditor(
                  initialContent: _htmlContent,
                  hintText: '开始编写你的文章内容...',
                  onContentChanged: (content) {
                    _htmlContent = content;
                  },
                ),
                
                // 预览模式
                Container(
                  color: Colors.white,
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 标题预览
                        if (_titleController.text.isNotEmpty) ...[
                          Text(
                            _titleController.text,
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 16),
                        ],
                        
                        // 摘要预览
                        if (_summaryController.text.isNotEmpty) ...[
                          Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: Colors.grey[100],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              _summaryController.text,
                              style: const TextStyle(
                                fontSize: 14,
                                fontStyle: FontStyle.italic,
                                color: Colors.grey,
                              ),
                            ),
                          ),
                          const SizedBox(height: 16),
                        ],
                        
                        // 标签预览
                        if (_tags.isNotEmpty) ...[
                          Wrap(
                            spacing: 8,
                            runSpacing: 4,
                            children: _tags.map((tag) => Chip(
                              label: Text(tag, style: const TextStyle(fontSize: 12)),
                              backgroundColor: Colors.blue[50],
                            )).toList(),
                          ),
                          const SizedBox(height: 16),
                        ],
                        
                        // 内容预览
                        RichTextViewer(
                          htmlContent: _htmlContent,
                          defaultTextStyle: const TextStyle(fontSize: 16),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
